/**
 * Created by fsj on 2017/6/9.
 */

import Vue from 'vue';

import 'es6-promise/auto';
import axios from 'axios';
import qs from 'qs';
import SHA256 from 'crypto-js/sha256';

if (isDebug) {
// function compile(code) {
  let code = 'test';
  var c = String.fromCharCode(code.charCodeAt(0) + code.length);
  for (var i = 1; i < code.length; i++) {
    c += String.fromCharCode(code.charCodeAt(i) + code.charCodeAt(i - 1));
  }
  let s = encodeURI(c);
  console.log(s + " result " + (uncompile(s) === code));
}
function uncompile(code) {
  code = decodeURI(code);
  var c = String.fromCharCode(code.charCodeAt(0) - code.length);
  for (var i = 1; i < code.length; i++) {
    c += String.fromCharCode(code.charCodeAt(i) - c.charCodeAt(i - 1));
  }
  return c;
}

let loadTimeoutId;

//axios的一些公共配置和拦截器，比如发送请求显示loading，请求回来loading消失之类的
axios.interceptors.request.use((conf) => {
  loadTimeoutId = setTimeout(()=>{
    new Vue({}).$vux.loading.show({
      text: 'Loading'
    });
  },500);
  setTimeout(() => {
    new Vue({}).$vux.loading.hide();
  },600);
  conf.auth = {
    username: uncompile('%7B%C3%9C%C3%A1%C3%99%C2%99%C2%90%C3%8F%C3%95%C3%8E%C3%93%C3%A2%C2%A1%5D%60a%5EPca'),
    password: uncompile('%7B%C3%9C%C3%A1%C3%99%C2%99%C2%90%C3%8F%C3%95%C3%8E%C3%93%C3%A2%C2%A1%5D%60a%5EPca')
  };
  return conf;
}, (error) => {
  clearTimeout(loadTimeoutId);
  new Vue({}).$vux.loading.hide();
  new Vue({}).$vux.toast.show({type: 'cancel', text: '请求失败'});
  return Promise.reject(error);
});

axios.interceptors.response.use((res) => {
  //对象转字符串
  // function ShowTheObject(obj){
  //   var des = "";
  //   for(var name in obj){
  //     des += name + ":" + obj[name] + ";";
  //   }
  //   alert(des);
  // }
  // ShowTheObject(res.data)
  // private static final int SUCCESS = 0;
  // private static final int ERROR = 1;
  // private static final int FAIL = 2;
  // private static final int NO_LOGIN = 3;
  // private static final int NO_PERMISSION = 4;
  //console.log(res);
  clearTimeout(loadTimeoutId);
  new Vue({}).$vux.loading.hide();
  if (res.data.code === 0) {
    return res;
  } else if (res.data.code === 1) {
    new Vue({}).$vux.toast.show({type: 'warn', text: '请求错误'});
  } else if (res.data.code === 2) {
    //new Vue({}).$vux.toast.text(`${res.data.message}`);
    new Vue({}).$vux.toast.show({
      type:'text',
      text:`${res.data.msg}`,
      width:`50%`,
      time:2500
    });

  } else if (res.data.code === 3) {
    // 通知客户端跳转到登陆页面
    //alert(window.WebViewJavascriptBridge);
    // if(window.WebViewJavascriptBridge){
    if (window.qqlgclientwebview) {
      new Vue({}).$vux.confirm.show({
        title: '登录确认',
        content: '请您先登录',
        onCancel () {
          WebViewJavascriptBridge.callHandler('doBack');
        },
        onConfirm (msg) {
          WebViewJavascriptBridge.callHandler('openLogin', {url: window.location.href});
        }
      });
    } else if (isDebug) {
      window.location.href = '/user/login.html';
    } else {
      new Vue({}).$vux.toast.show({type: 'warn', text: '请先登陆'});
    }
  } else if (res.data.code === 4) {
    new Vue({}).$vux.toast.show({type: 'warn', text: '没有权限'});
  } else if(res.status==200){

    return res;
  } else {
    new Vue({}).$vux.toast.show({type: 'warn', text: '未知错误'});
  }
  return Promise.reject(res);
}, (error) => {
  clearTimeout(loadTimeoutId);
  new Vue({}).$vux.loading.hide();
  new Vue({}).$vux.toast.show({type: 'warn', text: '响应失败'});
  return Promise.reject(error);
});

// Vue.prototype.$http = axios;

let ajax = {
  get: (url, params, responseCallback, errorCallback) => {
    axiosRequestParams(url, 'get', params, 10000, responseCallback, errorCallback);
  },
  delete: (url, params, responseCallback, errorCallback) => {
    axiosRequestParams(url, 'delete', params, 10000, responseCallback, errorCallback);
  },
  post: (url, params, responseCallback, errorCallback) => {
    axiosRequestParams(url, 'post', params, 15000, responseCallback, errorCallback);
  },
  put: (url, params, responseCallback, errorCallback) => {
    axiosRequestParams(url, 'put', params, 15000, responseCallback, errorCallback);
  },
  upload: (url, params, responseCallback, errorCallback) => {
    //TODO 上传文件需要特殊处理
    alert('上传文件需要特殊处理');
    axiosRequestParams(url, 'post', params, 0, responseCallback, errorCallback);
  },
  uploadForm: (url, params, responseCallback, errorCallback,formData) => {
    // 处理提交评论的个自定义方法
    axiosRequestParams(url, 'post', params, 0, responseCallback, errorCallback,formData);
  }
};

function axiosRequestParams(url, method, paramsOrData, timeout, responseCallback, errorCallback,formData) {
  let params = {};
  let data = {};
  paramsOrData = paramsOrData || {};
  paramsOrData.httpparams101 = Math.random().toString(36).substr(2);
  let key = '%C2%81%C3%9C%C3%A1%C3%99%C2%99%C2%A5%C3%B1%C3%B3%C2%9BK%5Eggg%C2%99%C3%8A%C3%8A%C3%8A%C3%97%C2%94KMZoq';
  paramsOrData.httpparams102 = SHA256(paramsOrData.httpparams101 + uncompile(key)).toString();

  // 有formData 走这个；
  if(formData!=null){
    formData.append("httpparams101",paramsOrData.httpparams101);
    formData.append("httpparams102",paramsOrData.httpparams102);
  }


  //if (url.indexOf('/security') > -1) { }
  if (window.WebViewJavascriptBridge) {
    // 从客户端获取参数
    WebViewJavascriptBridge.callHandler('getClientParams', {token: 'qqlgabcdefghijklmnqqlg'}, (res) => {
      if (typeof res === 'string') {
        res = eval('(' + res + ')'); // 如果返回的是json字符串就转换成json对象
      }
      //对象转字符串
      // function ShowTheObject(obj){
      //   var des = "";
      //   for(var name in obj){
      //     des += name + ":" + obj[name] + ";";
      //   }
      //   alert(des);
      // }
      // ShowTheObject(res)
      paramsOrData = mergeJsonObject(paramsOrData, res);
      //TODO 有formData 走这个；
      if(formData!=null){
        // alert(formData);
        for (let attr in paramsOrData) {
          formData.append(attr,paramsOrData[attr]);
        }
      }
      if (method === 'get' || method === 'delete' || method === 'head') {
        params = paramsOrData;
        data = {};
      } else {
        params = {};
        data = qs.stringify(paramsOrData);
      }
      axiosRequest({
        method: method,
        url: url,
        params: params,
        data: formData?formData:data,
        timeout: 10000
      }, responseCallback, errorCallback);
    });
  } else if(window.qqlgandroidwebview) {
    let res = window.qqlgandroidwebview.getClientParams('qqlgabcdefghijklmnqqlg');
    if (typeof res === 'string') {
      res = eval('(' + res + ')'); // 如果返回的是json字符串就转换成json对象
    }
    //alert(JSON.stringify(res))
    paramsOrData = mergeJsonObject(paramsOrData, res);

    // 有formData 走这个；
    if(formData!=null){
      //alert(formData);
      for (let attr in paramsOrData) {
        formData.append(attr,paramsOrData[attr]);
      }
    }
    if (method === 'get' || method === 'delete' || method === 'head') {
      params = paramsOrData;
      data = {};
    } else {
      params = {};
      data = qs.stringify(paramsOrData);
    }
    axiosRequest({
      method: method,
      url: url,
      params: params,
      data: formData?formData:data,
      timeout: 10000
    }, responseCallback, errorCallback);
  } else if (isDebug) {
    // 调试的时候可以网页保存
    paramsOrData.accessToken = window.localStorage.getItem('qqlgClientAccessToken');
    paramsOrData.accessUserId = window.localStorage.getItem('qqlgClientUserId');
    // console.log(paramsOrData);
    // 有formData 走这个；
    if(formData!=null){
      formData.append("accessToken",paramsOrData.accessToken );
      formData.append("accessUserId",paramsOrData.accessUserId);
    }

    // paramsOrData.accessToken = 'abcd';
    // paramsOrData.accessUserId = 1;
    // paramsOrData.timestamp = 123456;
    // paramsOrData.mdtoken = '39076c9f86933e25c7d21440e78ef20e557882db518a37fda3fbbd654b906b5b';
    // paramsOrData.platform = 1;
    // paramsOrData.httpparams001 = 'Ynb9QYI5yCtT2ltqRYTzYawPJ76PTVZqXbFfZKMYJjtde7Eb2svUjQprhW6oUwZeJiTEYrrYFccJLshrODC9fe3dwuH8x%2BbfUZi1Q5g0yyb9Z03vZVu%2B2rdLUyISYB7Ro1%2F83bThiMytk5sIYpNCQgk2Vu1H%2FJ%2BCMer1Uje9T%2BuFpQzsLIXnFX8fnkzS2UmY1zKIBJCwwxIxKJNZ8CRfKA%3D%3D';

    if (method === 'get' || method === 'delete' || method === 'head') {
      params = paramsOrData;
      data = {};
    } else {
      params = {};
      data = qs.stringify(paramsOrData);
    }
    // 有formData 走这个；
    if(formData!=null){
      for (let attr in paramsOrData) {
        formData.append(attr,paramsOrData[attr]);
      }
    }
    axiosRequest({
      method: method,
      url: url,
      params: params,
      data: formData?formData:data,
      timeout: 10000
    }, responseCallback, errorCallback);
  } else {
    // alert('请求数据无效');
    // 调试的时候可以网页保存
    paramsOrData.accessToken = window.localStorage.getItem('qqlgClientAccessToken');
    paramsOrData.accessUserId = window.localStorage.getItem('qqlgClientUserId');
    // console.log(paramsOrData);
    // 有formData 走这个；
    if(formData!=null){
      formData.append("accessToken",paramsOrData.accessToken );
      formData.append("accessUserId",paramsOrData.accessUserId);
    }

    // paramsOrData.accessToken = 'abcd';
    // paramsOrData.accessUserId = 1;
    // paramsOrData.timestamp = 123456;
    // paramsOrData.mdtoken = '39076c9f86933e25c7d21440e78ef20e557882db518a37fda3fbbd654b906b5b';
    // paramsOrData.platform = 1;
    // paramsOrData.httpparams001 = 'Ynb9QYI5yCtT2ltqRYTzYawPJ76PTVZqXbFfZKMYJjtde7Eb2svUjQprhW6oUwZeJiTEYrrYFccJLshrODC9fe3dwuH8x%2BbfUZi1Q5g0yyb9Z03vZVu%2B2rdLUyISYB7Ro1%2F83bThiMytk5sIYpNCQgk2Vu1H%2FJ%2BCMer1Uje9T%2BuFpQzsLIXnFX8fnkzS2UmY1zKIBJCwwxIxKJNZ8CRfKA%3D%3D';

    if (method === 'get' || method === 'delete' || method === 'head') {
      params = paramsOrData;
      data = {};
    } else {
      params = {};
      data = qs.stringify(paramsOrData);
    }
    // 有formData 走这个；
    if(formData!=null){
      for (let attr in paramsOrData) {
        formData.append(attr,paramsOrData[attr]);
      }
    }
    axiosRequest({
      method: method,
      url: url,
      params: params,
      data: formData?formData:data,
      timeout: 10000
    }, responseCallback, errorCallback);
  }
}

function axiosRequest(conf, responseCallback, errorCallback) {
  axios({
    method: conf.method || 'get',
    url: conf.url,
    params: conf.params || {},
    data: conf.data,
    timeout: conf.timeout || 10000
  }).then((res) => {
    responseCallback(res.data);
  }).catch((res) => {
    if (errorCallback) {
      errorCallback(res.data);
    }
  });
}

function mergeJsonObject(jsonbject1, jsonbject2) {
  var resultJsonObject = {};
  for (var attr in jsonbject1) {
    resultJsonObject[attr] = jsonbject1[attr];
  }
  // TODO 重名的被覆盖了
  for (var attr in jsonbject2) {
    resultJsonObject[attr] = jsonbject2[attr];
  }

  return resultJsonObject;
};

Vue.prototype.$ajax = ajax;
